package top.continew.admin.controller.distribute;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.shengchao.examstar.rpc.base.PageResult;
import cn.shengchao.examstar.rpc.base.TransResult;
import cn.shengchao.examstar.rpc.distribute.DistributeUserInviteApi;
import cn.shengchao.examstar.rpc.distribute.bi.DistributeNodeBI;
import cn.shengchao.examstar.rpc.distribute.dto.DistributeNodeInfoCreateDto;
import cn.shengchao.examstar.rpc.distribute.dto.DistributePersonUserCreateDto;
import cn.shengchao.examstar.rpc.distribute.enums.DistributeContentRoleEnum;
import cn.shengchao.examstar.rpc.distribute.enums.DistributeNodePropEnum;
import cn.shengchao.examstar.rpc.distribute.enums.DistributeSaleRoleEnum;
import cn.shengchao.examstar.rpc.distribute.enums.DistributeTypeEnum;
import cn.shengchao.examstar.rpc.distribute.resp.DistributeNodeInfoWithUpLevelRespEntity;
import cn.shengchao.examstar.rpc.uddsys.bi.PlatformUserArchBI;
import cn.shengchao.examstar.rpc.uddsys.bi.PlatformUserArchQueryBI;
import cn.shengchao.examstar.rpc.uddsys.req.DistributeUserInvitePageQuery;
import cn.shengchao.examstar.rpc.uddsys.req.DistributeUserProfitDetailPage;
import cn.shengchao.examstar.rpc.uddsys.req.PlatformDistributeUserPageQuery;
import cn.shengchao.examstar.rpc.uddsys.resp.*;
import cn.shengchao.examstar.rpc.wecom.api.CpUserServiceInviteApi;
import cn.shengchao.examstar.rpc.wecom.req.CpUserInvitePageQuery;
import cn.shengchao.examstar.rpc.wecom.resp.CpUserCustomerVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import top.continew.admin.business.service.UserHelperService;
import top.continew.admin.req.*;
import top.continew.admin.req.wecom.CpUserInviteSaveRto;
import top.continew.admin.system.model.vo.UserWithRoleVo;
import top.continew.admin.system.util.ValidateGroup;
import top.continew.starter.web.model.R;

import java.util.Arrays;
import java.util.List;

/**
 * @program: examstar-manger-api
 * @description: 平台分销用户操作
 * @author: Xiong weiqiang
 * @create: 2025-03-31 16:52
 */
@Tag(name = "分销-用户管理")
@RestController
@RequestMapping("/distribute/platformUser")
public class PlatformDistributeUserController {
    @DubboReference
    PlatformUserArchQueryBI platformUserArchQueryBIService;
    @DubboReference
    PlatformUserArchBI platformUserArchBI;
    @DubboReference
    DistributeNodeBI distributeNodeBI;
    @DubboReference
    DistributeUserInviteApi distributeUserInviteApi;
    @DubboReference
    CpUserServiceInviteApi cpUserServiceInviteApi;
    @Autowired
    UserHelperService userHelperService;
    @Operation(summary = "学员分销关系切换的保存（不能存在分销关系）", description = "学员分销关系切换的保存")
    @PostMapping("/studentDistributeInviteUpdate")
    R<String> studentDistributeInviteUpdate(@Validated@RequestBody DistributeUserInviteSaveRto saveRto) {
        UserWithRoleVo userExist=userHelperService.queryUserWithDistributeRole(saveRto.getUserId());
        if (userExist==null){
            return R.fail(R.fail().getCode(),"该用户不存在");
        }
        UserWithRoleVo userExist1=userHelperService.queryUserWithDistributeRole(saveRto.getDistributeUserId());
        if (userExist1==null||StrUtil.isBlank(userExist1.getRoleCodeListStr())||DistributeSaleRoleEnum.getByCode(userExist1.getRoleCodeListStr())==null){
            return R.fail(R.fail().getCode(),"提交的分销用户检查分销节点错误，节点不存在");
        }else if (DistributeSaleRoleEnum.getByCode(userExist1.getRoleCodeListStr())!=null&&DistributeSaleRoleEnum.ROLE_MKMG.getCode().equals(userExist1.getRoleCodeListStr())){
            return R.fail(R.fail().getCode(),"提交的分销用户检查分销节点错误，市场经理不能挂");
        }else{
            TransResult<String> transResult = distributeUserInviteApi.updateUserInviteRecord(saveRto.toSaveRto());
            if (transResult.getSuccess()){
                return R.ok();
            }else {
                return R.fail(R.fail().getCode(),transResult.getMessage());
            }
        }
    }
    /**
     * 用户的分销关系列表
     * @param pageQuery
     * @return
     */
    @Operation(summary = "用户的分销关系列表", description = "用户的分销关系列表")
    @GetMapping("/distributeInvitePageQuery")
    PageResult<DistributeUserInviteVo> distributeInvitePageQuery(DistributeUserInvitePageQuery pageQuery) {
        if (pageQuery==null){
            pageQuery = new DistributeUserInvitePageQuery();
            pageQuery.setPage(1);
            pageQuery.setSize(10);
        }
        return platformUserArchQueryBIService.queryDistributeUserInvitePage(pageQuery);
    }
    /**
     * 用户的邀请关系列表
     * @param pageQuery
     * @return
     */
    @Operation(summary = "用户的邀请关系列表", description = "用户的邀请关系列表")
    @GetMapping("/userInvitePageQuery")
    PageResult<CpUserCustomerVo> userInvitePageQuery(CpUserInvitePageQuery pageQuery) {
        if (pageQuery==null){
            pageQuery = new CpUserInvitePageQuery();
            pageQuery.setPage(1);
            pageQuery.setSize(10);
        }
        return cpUserServiceInviteApi.queryCpUserInvitePage(pageQuery);
    }

    @Operation(summary = "用户邀请切换的用户企微选项查询", description = "用户邀请切换的用户企微选项查询")
    @GetMapping("/userInviteSelectQuery")
    List<DistributeUserInviteSelectVo> userInviteSelectQuery(String searchValue) {
        return platformUserArchQueryBIService.listDistributeUserInviteSelectVo(searchValue);
    }

    @Operation(summary = "用户邀请企微切换的保存", description = "用户邀请企微切换的保存")
    @PostMapping("/updateInviteRelation")
    R<String> updateInviteRelation(@Validated@RequestBody CpUserInviteSaveRto saveRto) {
        boolean userExist=userHelperService.checkUserIdExist(saveRto.getUserId());
        if (!userExist){
            return R.fail(R.fail().getCode(),"用户不存在");
        }
        TransResult<String> transResult =cpUserServiceInviteApi.updateUserInviteRecord(saveRto.toSaveRto());
//                distributeUserInviteApi.updateUserInviteRecord(saveRto.toSaveRto());
        if (transResult.getSuccess()){
            return R.ok();
        }else {
            return R.fail(R.fail().getCode(),transResult.getMessage());
        }
    }


    /**
     * 分页查询分销市场经理列表
     * @param pageQuery
     * @return
     */
    @Operation(summary = "分销用户列表", description = "分销用户列表")
    @GetMapping("/salePageQuery")
    PageResult<DistributeUserVo> pageQuery(PlatformDistributeUserPageQuery pageQuery) {
        if (pageQuery==null){
            pageQuery = new PlatformDistributeUserPageQuery();
            pageQuery.setPage(1);
            pageQuery.setSize(10);
        }
        if (pageQuery.getUpDeptUserId()==null){
            pageQuery.setUpDeptUserId(0L);
        }
        if (pageQuery.getCodeQuery()!=null){
            if (pageQuery.getCodeQuery()==1){
                pageQuery.setDistributeRoleCodeList(Arrays.asList(DistributeSaleRoleEnum.ROLE_MKMG.getCode()));
            }else if (pageQuery.getCodeQuery()==2){
                pageQuery.setDistributeRoleCodeList(Arrays.asList(DistributeSaleRoleEnum.ROLE_DSPD.getCode()));
            }else if (pageQuery.getCodeQuery()==3){
                pageQuery.setDistributeRoleCodeList(Arrays.asList(DistributeSaleRoleEnum.ROLE_SLMB.getCode()));
            }
        }
        pageQuery.setDistributeType(DistributeTypeEnum.TYPE_SALE.getType());
        return platformUserArchQueryBIService.queryPlatformUserArchPage(pageQuery);
    }
    /**
     * 分页查询分销市场经理列表
     * @param pageQuery
     * @return
     */
    @Operation(summary = "内容分销用户列表", description = "内容分销用户列表")
    @GetMapping("/contentPageQuery")
    PageResult<DistributeUserVo> contentPageQuery(PlatformDistributeUserPageQuery pageQuery) {
        if (pageQuery==null){
            pageQuery = new PlatformDistributeUserPageQuery();
            pageQuery.setPage(1);
            pageQuery.setSize(10);
        }
        if (pageQuery.getUpDeptUserId()==null){
            pageQuery.setUpDeptUserId(0L);
        }
        if (pageQuery.getCodeQuery()!=null){
            if (pageQuery.getCodeQuery()==1){
                pageQuery.setDistributeRoleCodeList(Arrays.asList(DistributeContentRoleEnum.ROLE_CTPD.getCode()));
            }
        }
        pageQuery.setDistributeType(DistributeTypeEnum.TYPE_CTPD.getType());
        return platformUserArchQueryBIService.queryPlatformUserArchPage(pageQuery);
    }
    @Operation(summary = "代理人创建", description = "代理人创建")
    @PostMapping("/save")
    R save(@Validated(ValidateGroup.ReqGroup.SAVE.class) @RequestBody DistributeSaleProxyManagerUserCreateRto distributeSaleProxyManagerUserCreateRto) {
        DistributeSaleRoleEnum distributeSaleRoleEnum = DistributeSaleRoleEnum.getByCode(distributeSaleProxyManagerUserCreateRto.getDistributeRoleCode());
        if (distributeSaleRoleEnum==null){
            return R.fail(R.fail().getCode(), "分销角色不存在");
        }else{

            TransResult<String> transResult= TransResult.fail("未创建成功");
            switch (distributeSaleRoleEnum){
                case ROLE_MKMG:
                    DistributePersonUserCreateDto distributeNodeCreateDto = new DistributePersonUserCreateDto();
                    BeanUtil.copyProperties(distributeSaleProxyManagerUserCreateRto,distributeNodeCreateDto);
                    transResult=platformUserArchBI.createSaleDistributeMarketManagerAndRoleChain(distributeNodeCreateDto);
                    break;
                case ROLE_DSPD:
                    DistributeNodeInfoCreateDto distributeNodeInfoCreateDto1 = new DistributeNodeInfoCreateDto();
                    BeanUtil.copyProperties(distributeSaleProxyManagerUserCreateRto,distributeNodeInfoCreateDto1);
                    distributeNodeInfoCreateDto1.setUserType(DistributeNodePropEnum.TYPE_O.getProp());
                    transResult=platformUserArchBI.createSaleDistributeJmsAndRoleChain(distributeNodeInfoCreateDto1);
                    break;
                case ROLE_DSPD_EMP:
                    DistributePersonUserCreateDto distributeNodeCreateDto2 = new DistributePersonUserCreateDto();
                    BeanUtil.copyProperties(distributeSaleProxyManagerUserCreateRto,distributeNodeCreateDto2);
                    if (distributeSaleProxyManagerUserCreateRto.getUpLevelUserId()==0L){
                        return R.fail(R.fail().getCode(), "上级id不能是平台");
                    }else{
                        transResult=platformUserArchBI.createSaleDistributeJmsygAndRoleChain(distributeNodeCreateDto2);
                    }
                    break;
                case ROLE_SLMB:
                    DistributePersonUserCreateDto distributeNodeCreateDto3 = new DistributePersonUserCreateDto();
                    BeanUtil.copyProperties(distributeSaleProxyManagerUserCreateRto,distributeNodeCreateDto3);
                    transResult=platformUserArchBI.createSaleDistributeMemberAndRoleChain(distributeNodeCreateDto3);
                    break;
                default:
                    return R.fail(R.fail().getCode(), "不支持的用户角色");
            }

            return transResult.getSuccess()?R.ok():R.fail(R.fail().getCode(), transResult.getMessage());
        }

    }

    @Operation(summary = "内容代理创建", description = "内容代理创建")
    @PostMapping("/saveContent")
    R saveContent(@Validated(ValidateGroup.ReqGroup.SAVE.class) @RequestBody DistributeSaleProxyManagerUserCreateRto distributeSaleProxyManagerUserCreateRto) {
        DistributeContentRoleEnum distributeContentRoleEnum = DistributeContentRoleEnum.getByCode(distributeSaleProxyManagerUserCreateRto.getDistributeRoleCode());
        if (distributeContentRoleEnum==null){
            return R.fail(R.fail().getCode(), "内容代理不存在");
        }else{
            TransResult<String> transResult;
            switch (distributeContentRoleEnum){

                case ROLE_CTPD:
                    DistributeNodeInfoCreateDto distributeNodeInfoCreateDto1 = new DistributeNodeInfoCreateDto();
                    BeanUtil.copyProperties(distributeSaleProxyManagerUserCreateRto,distributeNodeInfoCreateDto1);
                    distributeNodeInfoCreateDto1.setUserType(DistributeNodePropEnum.TYPE_O.getProp());
                    transResult=platformUserArchBI.createContentDistributeJmsAndRoleChain(distributeNodeInfoCreateDto1);
                    break;
                case ROLE_CTPD_EMP:
                    DistributePersonUserCreateDto distributeNodeCreateDto2 = new DistributePersonUserCreateDto();
                    BeanUtil.copyProperties(distributeSaleProxyManagerUserCreateRto,distributeNodeCreateDto2);
                    if (distributeSaleProxyManagerUserCreateRto.getUpLevelUserId()==0L){
                        return R.fail(R.fail().getCode(), "上级id不能是平台");
                    }else{
                        transResult=platformUserArchBI.createContentDistributeJmsygAndRoleChain(distributeNodeCreateDto2);
                    }
                    break;
                default:
                    return R.fail(R.fail().getCode(), "不支持的内容代理");
            }
            return transResult.getSuccess()?R.ok():R.fail(R.fail().getCode(), transResult.getMessage());
        }

    }

    @Operation(summary = "推广分销代理人编辑保存", description = "推广分销代理人编辑保存")
    @PostMapping("/editSaleNodeInfo")
    R editSaleInfo(@Validated @RequestBody DistributeNodeInfoEditRto distributeNodeInfoEditRto) {
        distributeNodeInfoEditRto.setDistributeType(DistributeTypeEnum.TYPE_SALE.getType());
        platformUserArchBI.updateNodeInfo(DistributeNodeInfoEditRto.buildToReq(distributeNodeInfoEditRto));
        return R.ok();
    }

    @Operation(summary = "内容分销代理人编辑保存", description = "内容分销代理人编辑保存")
    @PostMapping("/editContentNodeInfo")
    R saveEditInfo(@Validated @RequestBody DistributeNodeInfoEditRto distributeNodeInfoEditRto) {
        distributeNodeInfoEditRto.setDistributeType(DistributeTypeEnum.TYPE_CTPD.getType());
        platformUserArchBI.updateNodeInfo(DistributeNodeInfoEditRto.buildToReq(distributeNodeInfoEditRto));
        return R.ok();
    }


    @Operation(summary = "推广分销代理人状态修改", description = "推广分销代理人状态修改")
    @PostMapping("/editSaleNodeState")
    R editSaleNodeState(@Validated @RequestBody DistributeNodeInfoStateRto distributeNodeInfoStateRto) {
        distributeNodeInfoStateRto.setDistributeType(DistributeTypeEnum.TYPE_SALE.getType());
        platformUserArchBI.updateNodeState(DistributeNodeInfoStateRto.buildToReq(distributeNodeInfoStateRto));
        return R.ok();
    }

    @Operation(summary = "内容分销代理人状态修改", description = "内容分销代理人状态修改")
    @PostMapping("/editContentNodeState")
    R editContentNodeState(@Validated @RequestBody DistributeNodeInfoStateRto distributeNodeInfoStateRto) {
        distributeNodeInfoStateRto.setDistributeType(DistributeTypeEnum.TYPE_CTPD.getType());
        platformUserArchBI.updateNodeState(DistributeNodeInfoStateRto.buildToReq(distributeNodeInfoStateRto));
        return R.ok();
    }

    @Operation(summary = "推广分销代理人收益详情", description = "推广分销代理人收益详情")
    @GetMapping("/getSaleUserMonthProfits/{userId}")
    R getSaleUserMonthProfits(@PathVariable("userId") Long userId) {
        List<DistributeUserProfitDetailVo> profitDetailVos=platformUserArchQueryBIService.selectDistributeUserMonthProfitDetailList(userId,DistributeTypeEnum.TYPE_SALE.getType());
        return R.ok(profitDetailVos);
    }

    @Operation(summary = "内容分销代理人收益详情", description = "内容分销代理人收益详情")
    @GetMapping("/getContentUserMonthProfits/{userId}")
    R getContentUserMonthProfits(@PathVariable("userId") Long userId) {
        List<DistributeUserProfitDetailVo> profitDetailVos=platformUserArchQueryBIService.selectDistributeUserMonthProfitDetailList(userId,DistributeTypeEnum.TYPE_CTPD.getType());
        return R.ok(profitDetailVos);
    }

    @Operation(summary = "推广分销代理人收益详情（分页）", description = "推广分销代理人收益详情（分页）")
    @GetMapping("/getSaleUserMonthProfitsPage")
    PageResult<DistributeUserProfitDetailVo> getSaleUserMonthProfitsPage(DistributeUserProfitDetailPage distributeUserProfitDetailPage) {
        if (distributeUserProfitDetailPage==null||distributeUserProfitDetailPage.getDistributeUserId()==null){
            return PageResult.of(0L, List.of());
        }
        distributeUserProfitDetailPage.setDistributeType(DistributeTypeEnum.TYPE_SALE.getType());
        return platformUserArchQueryBIService.selectDistributeUserProfitDetailPageList(distributeUserProfitDetailPage);
    }

    @Operation(summary = "内容分销代理人收益详情（分页）", description = "内容分销代理人收益详情（分页）")
    @GetMapping("/getContentUserMonthProfitsPage")
    PageResult<DistributeUserProfitDetailVo> getContentUserMonthProfitsPage(DistributeUserProfitDetailPage distributeUserProfitDetailPage) {
        if (distributeUserProfitDetailPage==null||distributeUserProfitDetailPage.getDistributeUserId()==null){
            return PageResult.of(0L, List.of());
        }
        distributeUserProfitDetailPage.setDistributeType(DistributeTypeEnum.TYPE_CTPD.getType());
        return platformUserArchQueryBIService.selectDistributeUserProfitDetailPageList(distributeUserProfitDetailPage);
    }
    @Operation(summary = "推广分销代理人换绑", description = "推广分销代理人换绑")
    @PostMapping("/changeSaleNodeUpLevelUser")
    R editSaleNodeState(@Validated @RequestBody DistributeNodeUserChangeUpLevelUserRto nodeUserChangeUpLevelUserRto) {
        TransResult<String> transResult=distributeNodeBI.changeSaleDistributeUserUpLevel(nodeUserChangeUpLevelUserRto.getUserId(),nodeUserChangeUpLevelUserRto.getDistributeRoleCode(),nodeUserChangeUpLevelUserRto.getUpperUserId());
        return transResult.getSuccess()?R.ok():R.fail(R.fail().getCode(), transResult.getMessage());
    }

    @Operation(summary = "内容分销员工换绑", description = "内容分销员工换绑")
    @PostMapping("/changeContentNodeUpLevelUser")
    R changeContentNodeUpLevelUser(@Validated @RequestBody DistributeNodeUserChangeUpLevelUserRto nodeUserChangeUpLevelUserRto) {
        TransResult<String> transResult=distributeNodeBI.changeContentDistributeUserUpLevel(nodeUserChangeUpLevelUserRto.getUserId(),nodeUserChangeUpLevelUserRto.getDistributeRoleCode(),nodeUserChangeUpLevelUserRto.getUpperUserId());
        return transResult.getSuccess()?R.ok():R.fail(R.fail().getCode(), transResult.getMessage());
    }

    @Operation(summary = "分销推广代理改比例", description = "分销推广代理改比例")
    @PostMapping("/changeSaleNodePercent")
    R changeSaleNodePercent(@Validated(ValidateGroup.ReqGroup.SAVE.class)  @RequestBody DistributeUserSalePercentChangeRto distributeUserSalePercentChangeRto) {
        platformUserArchBI.editDistributeUserStablePercent(DistributeUserSalePercentChangeRto.toDto(distributeUserSalePercentChangeRto));
        return R.ok();
    }
    @Operation(summary = "获取用户的推广分销节点详细", description = "获取用户的推广分销节点详细")
    @GetMapping("/getSaleDistributeUserNodeDetail/{userId}")
    R getSaleDistributeUserNodeDetail(@PathVariable("userId") Long userId) {
        DistributeNodeInfoWithUpLevelRespEntity queryDistributeNodeInfoWithUpLevel = distributeNodeBI.queryDistributeNodeInfoWithUpLevel(userId,DistributeTypeEnum.TYPE_SALE.getType());
        return R.ok(queryDistributeNodeInfoWithUpLevel);
    }

    @Operation(summary = "获取用户的内容分销节点详细", description = "获取用户的内容分销节点详细")
    @GetMapping("/getContentDistributeUserNodeDetail/{userId}")
    R getContentDistributeUserNodeDetail(@PathVariable("userId") Long userId) {
        DistributeNodeInfoWithUpLevelRespEntity queryDistributeNodeInfoWithUpLevel = distributeNodeBI.queryDistributeNodeInfoWithUpLevel(userId,DistributeTypeEnum.TYPE_CTPD.getType());
        return R.ok(queryDistributeNodeInfoWithUpLevel);
    }


    @Operation(summary = "获取推广用户的银行卡信息", description = "获取推广用户的银行卡信息")
    @GetMapping("/getSaleUserBank/{userId}")
    R<DistributeUserBankVo> getSaleUserBank(@PathVariable("userId") Long userId) {
        DistributeUserBankVo userBankVo = platformUserArchBI.getDistributeUserBankVo(userId,DistributeTypeEnum.TYPE_SALE.getType());
        return R.ok(userBankVo);
    }
    @Operation(summary = "获取内容用户的银行卡信息", description = "获取内容用户的银行卡信息")
    @GetMapping("/getContentUserBank/{userId}")
    R<DistributeUserBankVo> getContentUserBank(@PathVariable("userId") Long userId) {
        DistributeUserBankVo userBankVo = platformUserArchBI.getDistributeUserBankVo(userId,DistributeTypeEnum.TYPE_CTPD.getType());
        return R.ok(userBankVo);
    }


    @Operation(summary = "保存推广用户的银行卡信息", description = "保存推广用户的银行卡信息")
    @PostMapping("/saveSaleUserBank")
    R<String> saveSaleUserBank(@Validated @RequestBody DistributeUserBankRto bankSaveReq) {
        platformUserArchBI.saveDistributeUserBank(bankSaveReq.toDistributeUserBankSaveDto(DistributeTypeEnum.TYPE_SALE.getType()));
        return R.ok();
    }
    @Operation(summary = "保存内容用户的银行卡信息", description = "保存内容用户的银行卡信息")
    @PostMapping("/saveContentUserBank")
    R<String> saveContentUserBank(@Validated @RequestBody DistributeUserBankRto bankSaveReq) {
        platformUserArchBI.saveDistributeUserBank(bankSaveReq.toDistributeUserBankSaveDto(DistributeTypeEnum.TYPE_CTPD.getType()));
        return R.ok();
    }
}